namespace SS.WPF.Framework.ValidationRule
{
    using System.Globalization;
    using System.Text.RegularExpressions;
    using System.Windows.Controls;

    /// <summary>
    /// Expression validation rule
    /// </summary>
    public class RegexValidationRule : ValidationRule
    {
        /// <summary>
        /// Gets or sets RegularExpression.
        /// </summary>
        public string RegularExpression
        {
            get; set;
        }

        /// <summary>
        /// Validate the value match with expression or not
        /// </summary>
        /// <param name="value">
        /// The value. Should be string value
        /// </param>
        /// <param name="cultureInfo">
        /// The culture info.
        /// </param>
        /// <returns>
        /// ValidationResult to indicate validation result
        /// </returns>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var stringValue = value as string;
            if (stringValue == null)
            {
                return new ValidationResult(false, RegularExpression);
            }
            var match = Regex.Match(stringValue, RegularExpression);
            var isValid = (match.Success && (match.Index == 0)) && (match.Length == stringValue.Length);
            return new ValidationResult(isValid, RegularExpression ?? (object)this);
        }
    }
}